﻿function getType(type, format) {
  var newType = "";
  if (format === "($date-time)") {
    newType = "number";
  } else {
    switch (type) {
      case "integer":
      case "number":
        newType = "number";
        break;
      case "boolean":
        newType = "boolean";
        break;
      case "string":
        newType = "string";
        break;
      default:
        break;
    }
  }
  return newType;
}

function filter(target) {
  var obj = {};

  Array.from(
    target.getElementsByTagName("tbody")[0].getElementsByTagName("tr")
  ).forEach((element) => {
    var key = element.getElementsByTagName("td")[0].innerText;
    var posKey = element.getElementsByTagName("td")[1].innerText;
    var type = element.getElementsByTagName("td")[2].innerText;
    var desc = element.getElementsByTagName("td")[4].innerText;

    //对象max2层
    if (!obj[posKey]) {
      obj[posKey] = {};
    }
    obj[posKey][key] = {
      type,
      desc,
    };
  });


  const typeObj = {
    string: "string",
    integer: "number",
    long: "number",
    bigdecimal: "number",
    date: "string",
  };

  var filterStr = (key, item) => {
    return `
	 		/** ${item.desc} */
			${key}: ${typeObj[(item.type).toLowerCase()]};`;
  };

  function fil(ob) {
    var b = "{";

    Object.keys(ob).forEach((key, index) => {
      var item = ob[key];
      if ((item.type === "Object" || item.type === 'List[]') && obj[key]) {
        b += `
		/** ${item.desc} */
	   ${key}: ${fil(obj[key])};`;
      } else {
        b += filterStr(key, item);
      }
    });
    b += `
		}`;

    return b;
  }

  return fil(obj["body"] || obj["data"]);
}

document.addEventListener("DOMContentLoaded", function () {
  // 监听来自content-script的消息
  document.body.oncontextmenu = (event) => {
    var findDom = event.target.offsetParent;
    while (findDom && findDom.tagName !== "TABLE") {
      findDom = findDom.offsetParent;
      if (findDom && findDom.tagName === "BODY") {
        return;
      }
    }
    let data = findDom ? filter(findDom) : "";
    chrome.runtime.sendMessage({ data });
  };
});
